package guoanmaker.provider.business.service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import guoanmaker.provider.business.model.OperatorServerClass;
import guoanmaker.provider.business.model.ProviderBusiness;
import guoanmaker.provider.business.repository.OperatorServerClassRepository;
import guoanmaker.provider.business.repository.ProviderBusinessRepository;

/**
 * Created by Light on 2017/6/22.
 */
@Service
public class OperatorServerClassService {
    private final OperatorServerClassRepository provideServerClassRepository;
    
    private final ProviderBusinessRepository businessRepository;

    @Autowired
    public OperatorServerClassService(OperatorServerClassRepository provideServerClassRepository,ProviderBusinessRepository businessRepository) {
        this.provideServerClassRepository = provideServerClassRepository;
        this.businessRepository=businessRepository;
    }

    public OperatorServerClass saveServerClass(OperatorServerClass provideServerClass){
        return provideServerClassRepository.save(provideServerClass);
    }

    @PersistenceContext
	private EntityManager manager;
    
    /** 
    * @Title: findAll
    * @Description: 查询所有服务分类
    * @param    
    * @return 结果集合   
    * @throws 
    */
    public List<OperatorServerClass> getAllServerClass(){
        List<OperatorServerClass> provideServerClassList = provideServerClassRepository.findAll();
        ArrayList<OperatorServerClass> resultList = new ArrayList<OperatorServerClass>();
        if (provideServerClassList != null || !provideServerClassList.isEmpty()) {
            resultList.addAll(provideServerClassList);
        }
        return sortProvideServerClass(resultList);
    }
    /** 
    * @Title: getProviderClassByPage
    * @Description: 分页查询服务分类
    * @param： Integer page 当前页
     * @param: Integer size 每页条数   
    * @return Page<ProvideServerClass>    
    * @throws 
    */
    public Page<OperatorServerClass> getServerClassByPage(Integer page, Integer size){
        Sort sort = new Sort(Sort.Direction.ASC, "serverLevel");
        Pageable pageable = new PageRequest(page, size, sort);
        Page<OperatorServerClass> provideServerClassList = provideServerClassRepository.findAll(pageable);
        return provideServerClassList;
    }

    /** 
    * @Title: getServerClassById 
    * @Description: 根据ID查找服务分类
    * @param id   
    * @return    
    * @throws 
    */

    public OperatorServerClass getServerClassById(String id) {
        if (StringUtils.isEmpty(id)) {
            return null;
        }
        return provideServerClassRepository.findOne(id);
    }

    /** 
     * @Title: getServerClassByServerLevel
     * @Description: 根据服务分类级别查询
     * @param：id   
     * @return    
     * @throws 
     */
    public Page<OperatorServerClass> getServerClassByServerLevel(Integer page, Integer size, Integer serverLevel) {
        Pageable pageable = new PageRequest(page, size);
        Page<OperatorServerClass> provideServerClassesList = provideServerClassRepository.findAllByServerLevel(pageable, serverLevel);
        return provideServerClassesList;
    }
    
    /** 
     * @Title: getServerClassByServerLevel
     * @Description: 根据服务分类级别查询
     * @param：serverLevel
     * @return    
     * @throws 
     */
    public List<OperatorServerClass> getServerClassByServerLevel(Integer serverLevel) {
    	List<OperatorServerClass> provideServerClassesList = provideServerClassRepository.findByServerLevelAndDeleteStateIs(serverLevel,"0");
        return provideServerClassesList;
    }

    /** 
    * @Title: getServerClassByParentServerId 
    * @Description: 根据父项ID查询
    * @param: parentServerId  父项ID 
    * @return   
    * @throws 
    */
    public ArrayList<OperatorServerClass> getServerClassByParentServerId(String parentServerId) {
        if (StringUtils.isEmpty(parentServerId))
            return null;
        ArrayList<OperatorServerClass> provideServerClassArrayList = provideServerClassRepository.findAllByParentServerId(parentServerId);
        return provideServerClassArrayList;
    }

    /** 
     * @Title: deleteServerClass
     * @Description: 根据ID删除服务分类
     * @param：id   
     * @return    
     * @throws 
     */
    public void deleteServerClass(String id){
        provideServerClassRepository.delete(id);
    }

    /** 
    * @Title: sortProvideServerClass
    * @Description: ProvideServerClass集合排序
    * @param： ArrayList<ProvideServerClass>   
    * @return ArrayList<ProvideServerClass>    
    * @throws 
    */
    private static ArrayList<OperatorServerClass> sortProvideServerClass(ArrayList<OperatorServerClass> provideServerClassArrayList){
            provideServerClassArrayList.sort(new Comparator<OperatorServerClass>() {
                @Override
                public int compare(OperatorServerClass o1, OperatorServerClass o2) {
                    if (o1.getServerLevel() != o2.getServerLevel())
                        return o1.getServerLevel() - o2.getServerLevel();
                    else
                        return o1.getId().compareTo(o2.getId());
                }
            });
            return provideServerClassArrayList;
    }
    
  /**
   * 
  * @Title: getServerClassListForlevid 
  * @Description: 根据级别查询列表(这里用一句话描述这个方法的作用) 
  * @param serverLevel
  * @return    设定文件 
  * @return List<ProvideServerClass>    返回类型 
  * @throws 
   */
    public List<OperatorServerClass> getServerClassListForlevid(Integer serverLevel) {
       
    	List<OperatorServerClass> provideServerClassesList = provideServerClassRepository.findAllByServerforlevid(serverLevel);
        return provideServerClassesList;
    }

    /**
	 * @author baixsh
	 * @Description 查询商户提供的服务范围
	 * @param businessId 二级服务范围
	 * @return map
	 */
	public Map<String, Object> selectCommodityservice(String businessId) {
		Map<String, Object> remap=new HashMap<>();
		ProviderBusiness business=businessRepository.findOne(businessId);
		List<OperatorServerClass> twoPss=null;
		List<OperatorServerClass> onePss=null;
		List<OperatorServerClass> threePss=null;
		List<OperatorServerClass> fourPss=null;
		if(business!=null){
			String commodityService=business.getCommoditys();
			String[] commoditySs=commodityService.split(",");
			List twoIdList = new ArrayList(); 
			Collections	.addAll(twoIdList, commoditySs); 
			twoPss=provideServerClassRepository.findByIdInAndDeleteStateIs(twoIdList,"0");//查询商户服务的二级分类
			threePss=provideServerClassRepository.findByParentServerIdInAndDeleteStateIs(twoIdList,"0");//查询商户二级服务下的三级分类
			List threeIdList= new ArrayList(); //获取三级分类的id
			for(int i=0;i<threePss.size();i++){
				threeIdList.add(threePss.get(i).getId());
			}
			fourPss=provideServerClassRepository.findByParentServerIdInAndDeleteStateIs(threeIdList,"0");//查询商户三级服务下的四级分类
			List oneIdList= new ArrayList(); //获取一级分类的id
			Set<String> set=new HashSet<String>();
			for(int j=0;j<twoPss.size();j++){
				oneIdList.add(twoPss.get(j).getParentServerId());
			}
			set.addAll(oneIdList);
			oneIdList.clear();
			oneIdList.addAll(set);
			onePss=provideServerClassRepository.findByIdInAndDeleteStateIs(oneIdList,"0");//查询商户一级分类
		       
		}
		remap.put("twoPss",twoPss);
		remap.put("onePss",onePss);
		remap.put("threePss",threePss);
		remap.put("fourPss",fourPss);
		return remap;
	}
	
	 /** 
	    * @Title: 根据二级类别id获取下面子项id集合
	    * @Description: 根据父项ID查询
	    * @param: parentServerId  父项ID 
	    * @return   
	    * @throws 
	    */
	    public List<String> getServerIdByParentServerId(String service_type_id) {
	    	if (StringUtils.isEmpty(service_type_id))
		            return null;
	    	OperatorServerClass serverClass=provideServerClassRepository.findOne(service_type_id);//通过分类id获取分类对象
			List<String> ids=new ArrayList<>();
			if(serverClass!=null){
				Integer serverLevel=serverClass.getServerLevel();
				ArrayList<OperatorServerClass> provideServerClassArrayList = provideServerClassRepository.findAllByParentServerId(service_type_id);//获取二级或者三级下面的子标签
				if(provideServerClassArrayList!=null && provideServerClassArrayList.size()>0){
					for(int i=0;i<provideServerClassArrayList.size();i++){
						if(serverLevel==2){
							String parentId=provideServerClassArrayList.get(i).getId();//三级id
							ArrayList<OperatorServerClass> threeList = provideServerClassRepository.findAllByParentServerId(parentId);
							if(threeList!=null && threeList.size()>0){//如果三级分类下面存在四级分类，则将四级分类id放入ids集合；否则将当前三级分类id放入ids集合中
								for(int j=0;j<threeList.size();j++){
									ids.add(threeList.get(j).getId());
								}
							}else{
								ids.add(parentId);
							}
						}else{
							ids.add(provideServerClassArrayList.get(i).getId());
						}
					}
				}else{
					ids.add(service_type_id);
				}
			}else{
				ids.add(service_type_id);
			}
	        return ids;
	    }
	    
	    /**
		 * @author baixsh
		 * @Description 查询商户提供的二级服务范围和一级
		 * @param businessId 商户id
		 * @return map
		 */
		public Map<String, Object> selectBusinessService(String businessId) {
			Map<String, Object> remap=new HashMap<>();
			ProviderBusiness business=businessRepository.findOne(businessId);
			List<OperatorServerClass> twoPss=null;
			List<OperatorServerClass> onePss=null;
			if(business!=null){
				String commodityService=business.getCommoditys();
				String[] commoditySs=commodityService.split(",");
				List twoIdList = new ArrayList(); 
				Collections	.addAll(twoIdList, commoditySs); 
				twoPss=provideServerClassRepository.findByIdInAndDeleteStateIs(twoIdList,"0");//查询商户服务的二级分类
				List oneIdList= new ArrayList(); //获取一级分类的id
				Set<String> set=new HashSet<String>();
				for(int j=0;j<twoPss.size();j++){
					oneIdList.add(twoPss.get(j).getParentServerId());
				}
				set.addAll(oneIdList);
				oneIdList.clear();
				oneIdList.addAll(set);
				onePss=provideServerClassRepository.findByIdInAndDeleteStateIs(oneIdList,"0");//查询商户一级分类
				if(onePss.size()>0){
					for(int i=0;i<onePss.size();i++){
						List<OperatorServerClass> twoServerClasss=provideServerClassRepository.findByIdInAndParentServerIdIsAndDeleteStateIs(twoIdList, onePss.get(i).getId(),"0");
						onePss.get(i).setServerClasss(twoServerClasss);
					}
				}
			       
			}
			remap.put("onePss",onePss);
			remap.put("twoPss",twoPss);
			return remap;
		}

		//通过经营范围id和经营类型查询数据
		public List<OperatorServerClass> selectByIdAndServerType(String commoditys,Integer serverType){
			List<OperatorServerClass> lists=null;
			if(StringUtils.isNotEmpty(commoditys)){
				if(commoditys.contains(",")){
					List<String> userList = Arrays.asList(commoditys.split(","));
					lists=provideServerClassRepository.findByIdInAndServerTypeIsAndDeleteStateIs(userList, serverType,"0");
				}else{
					List<String> userList = new ArrayList<>();
					userList.add(commoditys);
					lists=provideServerClassRepository.findByIdInAndServerTypeIsAndDeleteStateIs(userList, serverType,"0");
				}
			}
			return lists;
		}
		
		//通过经营范围id和经营类型查询数据
		public List<OperatorServerClass> selectByIdAndServerLevel(String commoditys,Integer serverLevel){
			List<OperatorServerClass> lists=null;
			if(StringUtils.isNotEmpty(commoditys)){
				if(commoditys.contains(",")){
					List<String> userList = Arrays.asList(commoditys.split(","));
					lists=provideServerClassRepository.findByIdInAndServerLevelIsAndDeleteStateIs(userList, serverLevel,"0");
				}else{
					List<String> userList = new ArrayList<>();
					userList.add(commoditys);
					lists=provideServerClassRepository.findByIdInAndServerLevelIsAndDeleteStateIs(userList, serverLevel,"0");
				}
			}
			return lists;
		}
}
